﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using DevExpress.XtraBars;
using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraNavBar;
using DevExpress.XtraTreeList;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Helper;
using XCI.Sys.Model;

namespace XCI.Sys.Forms
{
    public partial class FrmStandardMain : ToolbarForm, IMainForm
    {
        private readonly bool menuLargeIcon = XmlHelper.GetAppSettings("menuLargeIcon", "false").ToBool();
        private ModuleHelper moduleHelper;
        private MainFormManager mainFormManager;
        private LoadingMask treeLoadingMask;
        public FrmStandardMain()
        {
            InitializeComponent();
            if (WinFormHelper.IsDesignMode()) WinFormHelper.InitDesignFont();
            SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
        }

        public ModuleHelper ModuleHelper => moduleHelper;
        public MainFormManager MainFormManager => mainFormManager;

        protected override void OnLoad(EventArgs e)
        {
            if (WinFormHelper.IsDesignMode()) WinFormHelper.InitDesignFont();
            base.OnLoad(e);
        }

        private async Task BindTreeData()
        {
            if (treeLoadingMask == null) treeLoadingMask = new LoadingMask(treeList);
            await treeLoadingMask.ShowAsync(async () =>
           {
               treeList.DataSource = SysApp.GetCurrentUserOwnModules().Where(p => p.IsMenu && p.IsWin).ToList();
               await moduleHelper.InitAsync(treeImageList, menuLargeIcon);
           });
        }

        private void TreeClick()
        {
            var entity = treeList.GetDataRecordByNode(treeList.FocusedNode);
            if (entity != null)
            {
                try
                {
                    // MdiClient client = this.Controls.OfType<MdiClient>().FirstOrDefault();
                    WaitFormHelper.Show("正在加载...", this);
                    mainFormManager.AddDocument(entity as SysModule);
                }
                finally
                {
                    WaitFormHelper.Hide();
                }
            }
        }

        private async void FrmStandardMain_Load(object sender, EventArgs e)
        {
            WinFormHelper.SetImageListSizeByDpiRatio(treeImageList, menuLargeIcon);
            navModule.OptionsNavPane.ExpandedWidth = Convert.ToInt32(navModule.OptionsNavPane.ExpandedWidth * WinFormHelper.GetDpiRatio());
            barController.PropertiesBar.LargeIcons = false;
            moduleHelper = new ModuleHelper(treeList);

            treeList.ViewInfo.PaintAppearance.HideSelectionRow.ForeColor = treeList.ViewInfo.PaintAppearance.FocusedRow.ForeColor;
            treeList.ViewInfo.PaintAppearance.HideSelectionRow.BackColor = treeList.ViewInfo.PaintAppearance.FocusedRow.BackColor;
            treeList.OptionsBehavior.AutoNodeHeight = false;
            treeList.RowHeight = Convert.ToInt32((menuLargeIcon ? 35 : 30) * WinFormHelper.GetDpiRatio());

            mainFormManager = new MainFormManager(this, mainTabbedView, menuLargeIcon);
            SysApp.MainFormManager = mainFormManager;
            mainFormManager.InitActiveUser();
            mainFormManager.SetStatusInfo(statusTime, statusUser, statusAccount, statusDept, statusOs, statusServer);
            await BindTreeData();
            navModule.OptionsNavPane.NavPaneState = NavPaneState.Expanded;
            mainFormManager.ShowHomeDocument();
        }

        private async void EditSearchModule_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var btn = editSearchModule.Properties.Buttons[0];
            btn.Enabled = false;
            SysApp.RefreshCurrentUserOwnModules();
            await BindTreeData();
            TimerHelper.DelayRun(5000, () => btn.Enabled = true);
        }

        private void EditSearchModule_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == R.EnterKey) treeList.ApplyFindFilter(editSearchModule.Text.Trim());
        }

        private void treeList1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                e.Handled = true;
                TreeClick();
            }
        }

        private void TreeList1_NodesReloaded(object sender, EventArgs e)
        {
            moduleHelper.ExpandNode();
        }

        private void treeModule_Click(object sender, EventArgs e)
        {
            if (e is MouseEventArgs ev)
            {
                HitInfoType info = treeList.CalcHitInfo(ev.Location).HitInfoType;
                if (info == HitInfoType.ColumnEdge || info == HitInfoType.Button || info == HitInfoType.Empty)
                {
                    return;
                }
            }
            TreeClick();
        }

        private void treeList1_GetStateImage(object sender, GetStateImageEventArgs e)
        {
            e.NodeImageIndex = moduleHelper.GetModuleImageIndex(e.Node);
        }

        private void btnMenuShowMain_ItemClick(object sender, ItemClickEventArgs e)
        {
            Show();
        }

        private void btnTheme_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.ShowThemeForm();
        }

        private void btnPwd_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.ShowModifyPasswordForm();
        }

        private void btnSwitchUser_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.SwitchUser();
        }

        private void btnAbout_ItemClick(object sender, ItemClickEventArgs e)
        {
            mainFormManager.ShowAboutForm();
        }

        public Form OwnForm => this;

        public void AddDocument(FormInfo info)
        {
            mainFormManager.AddDocument(info);
        }

        public void OnMessage(string message)
        {
            statusMsg.Caption = message;
        }
    }
}